package handler

import (
	"github.com/gin-gonic/gin"
	"shopping-order/consts"
	"time"

	"net/http"
	"shopping-order/api/request"
	"shopping-order/internal/dao"
	"shopping-order/internal/model"
	"shopping-order/pkg"
)

func RegisterUser(c *gin.Context) {
	var user model.User
	var req request.RegisterUserForm

	if req.Mobile == "" || req.Password == "" {
		c.JSON(http.StatusOK, gin.H{
			"code": 100000,
			"msg":  "验证失败",
			"data": nil,
		})
		return
	}

	err := dao.GetOneByFile(&model.User{Mobile: req.Mobile}, &user)
	if err != nil {
		c.JSON(http.StatusOK, gin.H{
			"code": 10000,
			"msg":  "查询失败",
			"data": false,
		})
		return
	}

	if user.Id > 0 {
		c.JSON(http.StatusOK, gin.H{
			"code": 10000,
			"msg":  "手机号已被使用",
			"data": false,
		})
		return
	}

	user = model.User{
		Mobile:   req.Mobile,
		Password: pkg.Md5(req.Password),
	}

	dao.AddFile(&user)

	c.JSON(http.StatusOK, gin.H{
		"code": http.StatusOK,
		"msg":  "注册成功",
		"data": true,
	})

}

func LoginUser(c *gin.Context) {
	var req request.LoginUserForm
	var user model.User

	if req.Mobile == "" || req.Password == "" {
		c.JSON(http.StatusOK, gin.H{
			"code": 10000,
			"msg":  "验证失败",
			"data": nil,
		})
		return
	}

	err := dao.GetOneByFile(&model.User{Mobile: req.Mobile}, &user)
	if err != nil {
		c.JSON(http.StatusOK, gin.H{
			"code": 10000,
			"msg":  "查询失败",
			"data": false,
		})
		return
	}

	if user.Id == 0 {
		c.JSON(http.StatusOK, gin.H{
			"code": 10000,
			"msg":  "账号或密码错误",
			"data": false,
		})
		return
	}

	if user.Password != pkg.Md5(req.Password) {
		c.JSON(http.StatusOK, gin.H{
			"code": 10000,
			"msg":  "账号或密码错误",
			"data": false,
		})
		return
	}

	token := pkg.CreateJwtToken(user.Id, time.Hour*24, consts.JWT_KEY)

	c.JSON(http.StatusOK, gin.H{
		"code": http.StatusOK,
		"msg":  "登陆成功",
		"data": token,
	})
}
